import React from 'react'
import { Row, Col, Input, message } from 'antd'
import { getArticleById } from '@/apiList/api'
import { RouteComponentProps } from 'react-router'
import SidebarMenu from '@/components/SidebarMenu/SidebarMenu'
import ArticleListItem from '@/components/Article/ArticleListItem'
import { getQueryObject } from '@/utils/jcore/page'
import { openPage } from '@/utils/tools'
import { IFArticle } from '@/store/reducer'

type P = {} & RouteComponentProps

type S = {
  list: IFArticle[]
  searchList: IFArticle[]
}

export default class ArticleList extends React.Component<P, S> {
  constructor(props: P) {
    super(props)
    this.state = {
      list: [],
      searchList: []
    }
  }
  UNSAFE_componentWillMount() {
    let query = getQueryObject(this.props.location.search)
    getArticleById({ id: query.id }).then((res) => {
      let list = res ? res.children : []
      this.setState({
        list,
        searchList: list
      })
    })
  }
  handel = (e: IFArticle) => {
    if (e.children) {
      let cur = e.children.find((a) => a.filePath.endsWith('index.html'))
      if (cur) {
        openPage(cur.filePath)
      } else {
        message.error('未找到以 index.html 结尾的入口文件 Σ(っ °Д °;)っ')
      }
    } else if (e.fileName.endsWith('.md')) {
      window.open(`/parseMarked/parseMarked.html?filePath=${e.filePath}`)
    } else {
      openPage(e.filePath)
    }
  }
  onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let searchList = this.state.list.filter((a) =>
      a.fileName.includes(e.target.value)
    )
    this.setState({ searchList })
  }
  render() {
    const { searchList } = this.state
    return (
      <div className="container pt-20">
        <Row>
          <Col xs={0} md={4}>
            <SidebarMenu />
          </Col>
          <Col xs={24} md={20}>
            <div className="mb-20">
              <Input
                placeholder="输入关键字搜索"
                allowClear
                size="large"
                onChange={this.onChange}
              />
            </div>
            {searchList.map((a) => (
              <ArticleListItem key={a.id} handel={this.handel} item={a} />
            ))}
          </Col>
        </Row>
      </div>
    )
  }
}
